﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using NExplorer.Core.Properties;

namespace NExplorer.Core.Commands
{
    public class InvertSelectionCommand : CommandBase
    {
        public InvertSelectionCommand()
            : base("Invert Selection", GetImage())
        {
            ServiceManager.Explorer.CurrentDirectoryChanged += WhenCurrentDirectoryChanged;
            WhenCurrentDirectoryChanged(null, null);
        }

        private void WhenCurrentDirectoryChanged(object sender, EventArgs e)
        {
            Enabled = ServiceManager.Explorer.CurrentDirectory != null;
        }

        private static Image GetImage()
        {
            Bitmap image = Resources.InvertSelection;
            image.MakeTransparent(Color.Magenta);

            return image;
        }

        public override void Execute()
        {
            base.Execute();

            List<FileSystemInfo> toSelect = new List<FileSystemInfo>();
            List<FileSystemInfo> selectedItems = new List<FileSystemInfo>(ServiceManager.Explorer.SelectedItems);

            foreach (FileSystemInfo info in ServiceManager.Explorer.CurrentDirectory.GetFileSystemInfos())
            {
                if (!selectedItems.Exists(fsi => fsi.FullName == info.FullName))
                {
                    toSelect.Add(info);
                }
            }

            ServiceManager.Explorer.SelectedItems = toSelect;
        }

        public override void Dispose()
        {
            base.Dispose();

            ServiceManager.Explorer.CurrentDirectoryChanged -= WhenCurrentDirectoryChanged;
        }
    }
}
